package com.cskaoyan.udp.edition2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/*
      接收端
 */
public class Receiver {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        // 1. 创建用于接收数据的DatagramSocket对象
        DatagramSocket datagramSocket = new DatagramSocket(9898);


        // 2. 准备接收数据的数据报包
        byte[] bytes = new byte[1024];
        DatagramPacket receivePacket = new DatagramPacket(bytes, 0, bytes.length);


        boolean flag = true;

        while (flag) {
            // 接收发送的数据
            String s = receiveData(datagramSocket, receivePacket);
            // 输出接收到的数据
            System.out.println(s);

            // 发送响应数据
            sendResponse(br, datagramSocket);


            if ("886".equals(s)) {
                // 根据自定义协议不在接收数据
                break;
            }
        }



        // 5. 关闭套接字
        datagramSocket.close();


    }

    private static void sendResponse(BufferedReader br, DatagramSocket datagramSocket) throws IOException {
        // 准备用于发送数据的数据报包
        String line = br.readLine();
        byte[] dataBytes = line.getBytes();
        InetAddress targetIp = InetAddress.getByName("127.0.0.1");
        int port = 9999;
        DatagramPacket sendPacket
                = new DatagramPacket(dataBytes, 0, dataBytes.length, targetIp, port);
        datagramSocket.send(sendPacket);
    }

    // 接收并解析数据
    private static String receiveData(DatagramSocket datagramSocket, DatagramPacket receivePacket) throws IOException {
       //// 3. 接收数据
        datagramSocket.receive(receivePacket);

        // 4. 解析接收到的数据
        byte[] data = receivePacket.getData();
        int offset = receivePacket.getOffset();
        int length = receivePacket.getLength();

        String s = new String(data, offset, length);
        return s;
    }
}
